package com.lfg.leetcode.leetcode0;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class No15ThreeSum {
    public static List<List<Integer>> threeSum(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        if (nums.length < 3) {
            return ret;
        }
        Arrays.sort(nums);
        for (int i = 0; i < nums.length; i++) {
            if (i > 0 && nums[i] == nums[i - 1]) {
                continue;
            }
            int n = i + 1;
            int m = nums.length - 1;
            while (n < m) {

                if (nums[n] + nums[m] + nums[i] == 0) {
                    List<Integer> l = new ArrayList<Integer>();
                    l.add(nums[n]);
                    l.add(nums[m]);
                    l.add(nums[i]);
                    Collections.sort(l);
                    ret.add(l);
                    n++;
                    m--;
                    while (n > 0 && n < nums.length && nums[n] == nums[n - 1]) {
                        n++;
                    }
                } else if (-nums[i] - nums[n] >= nums[m]) {
                    n++;
                    while (n > 0 && n < nums.length && nums[n] == nums[n - 1]) {
                        n++;
                    }
                } else {
                    m--;
                }

            }
        }
        return ret;
    }


    public static void main(String[] args) {
        System.out.println(threeSum(new int[]{-4, -2, -2, -2, 0, 1, 2, 2, 2, 3, 3, 4, 4, 6, 6}));
//        System.out.println(threeSum(new int[]{-1,0,1,2,-1,-4}));
//        System.out.println(threeSum(new int[]{-2,0,0,2,2}));
    }
}
